<?php
class CTagsModel extends CommonModel {
    protected $tableName="tags";//对应表名
    
    
    function GetArcList($tagname=""){
        $where=array(
            "t.tagname"=>$tagname,
        );
        $list=$this->alias('t')->field('t.tagname,m.*')->join("inner join __ARCTAG__ as a on a.tid=t.id")->join("inner join __ARCTINY__ m on m.id=a.aid")->where($where)->select();
        
        $list=D('CArchive')->listAddonField($list);
        
        return $list;
    }
    /**
     * 获取指定文档的tags的链接
     * @param 文档id $aid
     * @param int $row 需要的tag链接数量
     * @return string tag链接
     */
    function GetTagsLink($aid="0",$row=0){
        $taglist=$this->GetTags($aid);
        $links="";
        if(!empty($taglist)){
            $i=1;
            foreach($taglist as $tag){
                if($row>0 && $i>$row){
                    break;
                }
                $links.="<a href='".$this->BuildTagUrl($tag['tagname'])."'>{$tag['tagname']}</a> ";
                $i++;
            }
        }
        return $links;
    }
    
    //建立tag链接
    function BuildTagUrl($tagname){
        $tagname=rawurlencode($tagname);//对tag名进行urlencode
        return _U("/tag/view/".$tagname);
    }
    
    //获取指定文档的tags列表
    function GetTags($aid){
        static $_list=array();
        if(!empty($_list[$aid])){
            return $_list[$aid];
        }
        $where=array(
            "a.aid"=>$aid,
        );
        $field="t.tagname";
        $_list[$aid]=$this->field($field)->alias("t")->join("inner join __ARCTAG__ as a on a.tid=t.id")->where($where)->select();
        return $_list[$aid];
    }
    
    //获取标签列表
    function GetTagList($row=10){
        $list=$this->field(TRUE)->page(1,$row)->select();
        foreach($list as $k=>$v){
            $v['tagurl']=$this->BuildTagUrl($v['tagname']);
            $v['color']=randstr("red","green","blue","yellow");
            $list[$k]=$v;
        }
        return $list;
    }
}
